﻿using System;
using System.Collections.Generic;

namespace CommonEngine.Resource
{
    /// <summary>
    /// 条件数据封装
    /// </summary>
    public class Condition : ICondition
    {
        public static readonly Type GuidType = typeof(Guid);
        public static readonly Type DateTimeType = typeof(DateTime);
        public static readonly Type IntegerType = typeof(Int32);

        public string Name { get; set; }
        public string TableName { get; set; }
        public string PropertyName { get; set; }

        public ConditionOperationType OperationType { get; set; }
        public ConditionValueType ValueType { get; set; }

        public Func<List<ValueNode>> GetInitialDataList { get; set; }

        public Type CLRValueType
        {
            get
            {
                switch (this.ValueType)
                {
                    case ConditionValueType.Guid:
                        return GuidType;
                    case ConditionValueType.DateTime:
                        return DateTimeType;
                    case ConditionValueType.Integer:
                        return IntegerType;
                    case ConditionValueType.String:
                        return typeof(string);
                    default:
                        throw new ArgumentOutOfRangeException(string.Format("Condition value type {0} has no mapped CLR type.", this.ValueType.ToString()));
                }
            }
        }

        internal static TValue GetValueFromString<TValue>(string value)
        {
            Type valueType = typeof(TValue);

            object result;

            if (valueType == GuidType)
            {
                result = Guid.Parse(value);
            }
            else if (valueType == DateTimeType)
            {
                result = DateTime.Parse(value);
            }
            else
            {
                result = Int32.Parse(value);
            }
            return (TValue)result;
        }

        internal static string ConvertValueToString(object value)
        {
            string result;

            if (value is DateTime)
            {
                result = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                result = value.ToString();
            }
            return result;
        }
    }
}
